import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

data = pd.read_csv('../data/examdata.csv')
# print(data.head())

#数据可视化
fig1 = plt.figure()
mask = data.loc[:,'Pass'] == 1
passed = plt.scatter(data.loc[:,'Exam1'][mask],data.loc[:,'Exam2'][mask])
failed = plt.scatter(data.loc[:,'Exam1'][~mask],data.loc[:,'Exam2'][~mask])
plt.title('Exam1 2 - Exam2')
plt.xlabel('Exam1')
plt.ylabel('Exam2')
plt.legend((passed,failed),('Passed','Failed'))

#赋值
x = data.drop('Pass',axis=1)
x1 = data.loc[:,'Exam1']
x2 = data.loc[:,'Exam2']
y = data.loc[:,'Pass']

#establish model and train it
logistic_model = LogisticRegression()
logistic_model.fit(x,y)

y_predict = logistic_model.predict(x)
# print(y_predict)

accuracy_score  = accuracy_score(y,y_predict)
# print('Accuracy:',accuracy_score)

y_test = logistic_model.predict([[45,65]])
# print('pass' if y_test == 1 else 'failed')

theta0 = logistic_model.intercept_
theta1 = logistic_model.coef_[0][0]
theta2 = logistic_model.coef_[0][1]

#一阶边界函数
x2_new = -(theta0 + theta1*x1) / theta2
# plt.plot(x1,x2_new)
# plt.show()

#二阶边界函数
x1_2 = x1 * x1;
x2_2 = x2 * x2;
x1_x2 = x1 * x2;
X_new = {'x1':x1,'x2':x2,'x1_2':x1_2,'x2_2':x2_2,'x1_x2':x1_x2}
X_new = pd.DataFrame(X_new)
print(X_new.head())

LR2 = LogisticRegression(solver='lbfgs', C=1.0, max_iter=1000)
LR2.fit(X_new,y)

y2_predict = LR2.predict(X_new)
accuracy2 = accuracy_score(y,y2_predict)
print(accuracy2)